import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusLocator;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.code.DataType;
import com.serotonin.modbus4j.code.RegisterRange;
import com.serotonin.modbus4j.exception.ErrorResponseException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.ip.IpParameters;


public class Communication {
	
	private ModbusMaster master = null;  
	
	public void InitModbus(){
        IpParameters ipParameters = new IpParameters();
        ipParameters.setHost("117.236.217.109");
        ipParameters.setPort(502);
        ipParameters.setEncapsulated(false);

        ModbusFactory factory = new ModbusFactory();
        
        try{
            this.master = factory.createTcpMaster(ipParameters, true);
            this.master.setTimeout(1500);
            this.master.setRetries(5);
            this.master.init();     
        }catch (Exception e) {
            //throw new IOCommunicationException(e , ErrorConstants.MODBUS_INITIALIZATING_ERR);
        } 
    }
	
	 public void WriteData(int data, int offset){
	        int slaveId = 1;
	        int range = RegisterRange.HOLDING_REGISTER;
	        ModbusLocator loc = new ModbusLocator(slaveId, range, offset, DataType.FOUR_BYTE_INT_UNSIGNED);
	        try {
	            int value = data;            
	            master.setValue(loc, value);
	            int result = ((Number)master.getValue(loc)).intValue();
	        } catch (ModbusTransportException e) {
	            
	        } catch (ErrorResponseException e) {
	            //Debugger.e("Modbus error response error " , e);
	            //throw new IOCommunicationResponseException(e ,(int) e.getErrorResponse().getExceptionCode());
	        }        
	    }
	    

}
